var imagesToLoad = [];
var videosToLoad = [];

function beginAll() {
	loadImagesArray();
}

function loadImagesArray() {
	var client = new XMLHttpRequest();
	//client.open('GET', 'http://www.angiemarin.com/images.txt', true);
	client.open('GET', 'Assets/images.txt', true);

	client.onreadystatechange = function() {
		imagesToLoad = client.responseText.split('\n');
		if(client.readyState == 4) {
			loadImagesIntoPage(imagesToLoad);
		}
	}

	client.send();
}

function loadImagesIntoPage(imagesArray) {
	imagesArray.forEach(function (imageUrl, index) {
		//Check that image url has something
		if(imageUrl.length <= 0) {
			return;
		}
		
		var rawImageName = imageUrl;
		imageUrl = "Assets/pixelimg/" + imageUrl;
		var id = "image_" + index;
		var divParent = document.getElementById("right");
		var parentWidth = divParent.clientWidth;
		var parentHeight = divParent.clientHeight;
		var padding = "";
		
		//Set padding from first image
		if(index > 0) {
			padding = "padding-top:10px;";
		}
		
		divParent.innerHTML += "<img id=" 
			+ id  
			+ " style='display:block;margin-left:auto;margin-right:auto;" 
			+ padding 
			+ "' src='" + imageUrl + "' "
			+ " onmouseover=onImageMouseOver(this);"
			+ " onmouseleave=onImageMouseLeave(this);"
			+ " />";
			
		var img = document.getElementById(id); 
		img.imageId = rawImageName;
		//img.addEventListener("onmouseover", function () { onImageMouseOver(img) }, false);
		//img.onmouseleave = onImageMouseLeave(img);
		
		//or however you get a handle to the IMG
		var imgWidth = img.clientWidth;
		var imgHeight = img.clientHeight;
		
		if(imgWidth > parentWidth) {
			var scaleFactor = parentWidth / imgWidth;
			img.style.width = (imgWidth * scaleFactor) + "px";
			img.style.height = (imgHeight * scaleFactor) + "px";
		}
	}, this);
}

function onImageMouseOver(target) {
	console.log("Image clicked! " + target);
	target.src = target.src.replace("pixelimg", "img");
}

function onImageMouseLeave(target) {
	target.src = target.src.replace("img", "pixelimg");
}

function onVideoLinkClicked () {	
	showImages(false);
	showFrameByName("iframeRender", true);
}

function onImageLinkClicked () {
	showImages(true);
	showFrameByName("iframeRender", false);
}

function showFrameByName(frameName, visible) {
	var iFrame = document.getElementById(frameName);
	if(visible) {
		iFrame.style.display = "block";
	} else {
		iFrame.style.display = "none";
	}
}

function showImages(visible) {
	var divParent = document.getElementById("right");
	var images = divParent.getElementsByTagName("img");
	for(var i = 0; i < images.length; ++i) {
		if(visible) {
			images[i].style.display = "block";
		} else {
			images[i].style.display = "none";
		}
	}
}